package com.eric.husky.service;

import com.eric.husky.common.enums.LoginEnum;
import com.eric.husky.common.exception.CmdcException;
import com.eric.husky.common.exception.ErrorEnum;
import com.eric.husky.common.utils.CommonsUtils;
import com.eric.husky.common.utils.RedisUtil;
import com.eric.husky.common.utils.TokenUtil;
import com.eric.husky.common.utils.UpdateUtil;
import com.eric.husky.common.web.Constant;
import com.eric.husky.common.web.ResponseModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.eric.husky.dao.UserDao;
import com.eric.husky.bean.User;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Slf4j
@Service
public class UserService {
    @Autowired
	private UserDao userDao;
	@Autowired
	RedisUtil redisUtil;

	public Page<User> list(User user, Pageable page) {
		Example<User> example = Example.of(user);
		return userDao.findAll(example, page);
	}

	public User get(Integer userid) {
		return userDao.findById(userid).get();
	}

    public List<User> findList() {
		return userDao.findAll();
	}

    public User findByPhone(String phone) {
		List<User> users = userDao.findByPhone(phone);
		return users.size()==1 ? users.get(0):null;
	}

	@Transactional
	public User save(User user) {
	    if(user.getUserid()!=null){
	        User userOld = userDao.findById(user.getUserid()).orElse(null);
	        if(userOld!=null){
	            UpdateUtil.copyNullProperties(user,userOld);
                return userDao.save(userOld);
	        }
	    }
	    return userDao.save(user);
	}

	@Transactional
	public void delete(Integer userid) {
		userDao.deleteById(userid);
	}

	@Transactional
	public void updatePwd(Integer userId,String password) {
		userDao.updatePwd(userId,password);
	}

	@Transactional
	public ResponseModel register(User user,HttpServletResponse response) {
		// 首先检查此用户是否在数据库
		if (this.findByPhone(user.getPhone()) != null) throw new CmdcException(500, "该手机号已经注册");
		// 制作用户密码,然后将用户插入user表中
		String encryptPassword = CommonsUtils.encryptPassword(user.getPassword(), String.valueOf(user.getPhone()));
		log.info("加密之后的用户密码是:{}", encryptPassword);
		user.setPassword(encryptPassword);
		// 增加用户角色中间表,注册最基本角色
		Long currentTimeMillis = System.currentTimeMillis();
		String token= TokenUtil.sign(user.getPhone(),currentTimeMillis);
		redisUtil.set(user.getPhone(),currentTimeMillis,TokenUtil.REFRESH_EXPIRE_TIME);
		response.setHeader("Authorization", token);
		response.setHeader("Access-Control-Expose-Headers", "Authorization");
		return ResponseModel.success(userDao.save(user));
	}

	public ResponseModel userLogin(String username,String password, HttpServletResponse response) {
		// 校验userId是否为空
		if (StringUtils.isEmpty(username)) throw new CmdcException(ErrorEnum.ACCOUNT_UNUSUAL);
		// 校验数据库中此user是否存在
		User user = this.findByPhone(username);
		if (user == null ) throw new CmdcException(ErrorEnum.ACCOUNT_UNUSUAL);

		Long currentTimeMillis = System.currentTimeMillis();
		String token= TokenUtil.sign(username,currentTimeMillis);
		redisUtil.set(username,currentTimeMillis,TokenUtil.REFRESH_EXPIRE_TIME);

		response.setHeader("Authorization", token);
		response.setHeader("Access-Control-Expose-Headers", "Authorization");
		// 若登陆成功返回相关token
		return ResponseModel.success(user);
	}


}